<?php
class User {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 创建子账号
     * @method POST
     * @route /user/createSubAccount
     */
    public function createSubAccount(): void {
        // 验证当前用户是否有资格创建子账号
        $parentUserId = $this->auth->getUserId();
        if ($parentUserId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        // 检查父账号是否为企业版或团队版
        $stmt = $this->conn->prepare("SELECT version FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $parentUserId]);
        $parentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$parentUser || !in_array($parentUser['version'], [3, 4])) {
            throw new Exception("只有团队版或企业版用户才能添加子账号", 400);
        }
        
        // 获取父账号的公司信息
        $stmt = $this->conn->prepare("SELECT mobile, company_id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $parentUserId]);
        $parentInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$parentInfo) {
            throw new Exception("获取父账号信息失败", 500);
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['username']) || empty($data['password']) || empty($data['real_name'])) {
            throw new Exception("缺少必填字段", 400);
        }
        
        // 验证子账号用户名格式和长度
        if (empty($data['username']) || mb_strlen($data['username'], 'UTF-8') < 2 || mb_strlen($data['username'], 'UTF-8') > 20) {
            throw new Exception("子账号用户名长度应为2-20位", 400);
        }
        
        // 检查子账号用户名是否已存在
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE username = :username LIMIT 1");
        $stmt->execute([':username' => $data['username']]);
        if ($stmt->fetch()) {
            throw new Exception("子账号用户名已存在", 409);
        }
        
        // 密码哈希处理
        $hashedPassword = Security::hashPassword($data['password']);
        
        // 检查前端传递的参数，如果有mobile字段但没有sub_mobile字段，就将mobile值赋给sub_mobile
        if (!empty($data['mobile']) && empty($data['sub_mobile'])) {
            $data['sub_mobile'] = $data['mobile'];
        }
        
        // 如果提供了superior_id，验证它对应的用户存在且是管理员
        if (isset($data['superior_id']) && !empty($data['superior_id'])) {
            $stmt = $this->conn->prepare("SELECT id FROM users WHERE id = :id AND permission = 'admin' LIMIT 1");
            $stmt->execute([':id' => $data['superior_id']]);
            if (!$stmt->fetch()) {
                throw new Exception("指定的管理员不存在", 404);
            }
        }
        
        // 子账号数据处理
        $userData = [
            ':username' => $data['username'],
            ':password' => $hashedPassword,
            // 为子账号生成唯一的mobile值（原字段为唯一索引，不能重复使用父账号的mobile）
            ':mobile' => 'sub_' . $parentUserId . '_' . time() . '_' . rand(1000, 9999),
            // 真实姓名
            ':real_name' => $data['real_name'],
            // 职位
            ':position' => $data['position'] ?? '',
            // 权限设置：子账号只能是admin(员工管理员)或member(普通员工)，不能设置为superadmin(系统超级管理员)
            ':permission' => ($data['role'] === 1 || $data['role'] === 'admin') ? 'admin' : 'member',
            // 公司ID
            ':company_id' => $parentInfo['company_id'],
            // 状态
            ':status' => $data['status'] ?? 1,
            // 创建时间
            ':create_time' => time(),
            // 最后登录时间
            ':last_login_time' => 0,
            // 版本（默认个人版）
            ':version' => 1,
            // 标记为子账号
            ':is_sub' => 1,
            // 父账号ID
            ':parent_user_id' => $parentUserId,
            // 新增字段：电子邮箱
            ':email' => $data['email'] ?? '',
            // 新增字段：性别（0=未知, 1=男, 2=女）
            ':gender' => isset($data['gender']) && in_array(intval($data['gender']), [0, 1, 2]) ? intval($data['gender']) : 0,
            // 新增字段：底薪
            ':basic_salary' => isset($data['basic_salary']) ? floatval($data['basic_salary']) : 0.00,
            // 新增字段：子账号独立手机号（可为空，但唯一）
            ':sub_mobile' => $data['sub_mobile'] ?? null,
            // 新增字段：头像
            ':avatar' => $data['avatar'] ?? null,
            // 新增字段：所属管理员ID
            ':superior_id' => $data['superior_id'] ?? null
        ];
        
        // 如果提供了子账号手机号，验证其唯一性
        if (!empty($data['sub_mobile'])) {
            $stmt = $this->conn->prepare("SELECT id FROM users WHERE sub_mobile = :sub_mobile LIMIT 1");
            $stmt->execute([':sub_mobile' => $data['sub_mobile']]);
            if ($stmt->fetch()) {
                throw new Exception("子账号手机号已存在", 409);
            }
        }
        
        // 插入子账号数据到users表，包含所有新增字段
        $stmt = $this->conn->prepare(
            "
            INSERT INTO users (username, password, mobile, real_name, position, permission, company_id, status, create_time, last_login_time, version, is_sub, parent_user_id, email, gender, basic_salary, sub_mobile, avatar, superior_id)
            VALUES (:username, :password, :mobile, :real_name, :position, :permission, :company_id, :status, :create_time, :last_login_time, :version, :is_sub, :parent_user_id, :email, :gender, :basic_salary, :sub_mobile, :avatar, :superior_id)
        ");
        
        if (!$stmt->execute($userData)) {
            throw new Exception("添加子账号失败", 500);
        }
        
        $subAccountId = $this->conn->lastInsertId();
        
        echo json_encode([
            'code' => 200,
            'msg' => '添加子账号成功',
            'data' => [
                'sub_account_id' => $subAccountId
            ]
        ]);
    }

    /**
     * 获取客户列表 (需要管理员权限)
     * @method GET
     * @route /user/customer
     * 支持权限：superadmin, assistant
     */
    public function customer(): void {
        $this->auth->checkAdmin();
        
        // 获取当前登录用户信息
        $currentUserId = $this->auth->getUserId();
        $stmt = $this->conn->prepare("SELECT permission, position, company_id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $currentUserId]);
        $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(50, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = [];
        $params = [];
        
        // 基础条件：is_sub==0 且 permission不是superadmin或assistant的用户
        $where[] = "u.is_sub = 0";
        $where[] = "u.permission NOT IN (:permission1, :permission2)";
        $params[':permission1'] = 'superadmin';
        $params[':permission2'] = 'assistant';
        
        // 根据当前用户权限进行过滤
        // if ($currentUser['permission'] !== 'superadmin') {
        //     // 非超级管理员只能查看同一公司的用户
        //     if ($currentUser['company_id'] === null) {
        //         // 处理company_id为null的情况
        //         $where[] = "u.company_id IS NULL";
        //     } else {
        //         $where[] = "u.company_id = :current_company_id";
        //         $params[':current_company_id'] = $currentUser['company_id'];
        //     }
            
        //     // 根据职位进行过滤
        //     if ($currentUser['permission'] === 'admin') {
        //         if ($currentUser['position'] === '拍摄主管') {
        //             $where[] = "u.position IN (:position1, :position2)";
        //             $params[':position1'] = '摄影师';
        //             $params[':position2'] = '录像师';
        //         } else if ($currentUser['position'] === '后期主管') {
        //             $where[] = "u.position IN (:position1, :position2)";
        //             $params[':position1'] = '照片修图师';
        //             $params[':position2'] = '视频剪辑师';
        //         } else if ($currentUser['position'] === '市场主管') {
        //             $where[] = "u.position IN (:position1, :position2, :position3)";
        //             $params[':position1'] = '市场运营';
        //             $params[':position2'] = '市场销售';
        //             $params[':position3'] = '售后客服';
        //         } else {
        //             // 其他管理员只能查看普通用户
        //             $where[] = "u.permission = 'member'";
        //         }
        //     } else {
        //         // 普通用户只能查看自己
        //         $where[] = "u.id = :current_user_id";
        //         $params[':current_user_id'] = $currentUserId;
        //     }
        // }
        
        // 筛选选项：用户名、真实姓名、手机号
        if (!empty($_GET['keyword'])) {
            $keyword = '%' . $_GET['keyword'] . '%';
            $where[] = "(u.username LIKE :keyword OR u.real_name LIKE :keyword OR u.mobile LIKE :keyword)";
            $params[':keyword'] = $keyword;
        }

        // 筛选选项：状态
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "u.status = :status";
            $params[':status'] = intval($_GET['status']);
        }

        // 筛选选项：用户版本
        if (isset($_GET['version']) && $_GET['version'] !== '') {
            $where[] = "u.version = :version";
            $params[':version'] = intval($_GET['version']);
        }
        
        // 筛选选项：所属公司
        if (isset($_GET['company_id']) && $_GET['company_id'] !== '' && $currentUser['permission'] === 'superadmin') {
            $where[] = "u.company_id = :company_id";
            $params[':company_id'] = intval($_GET['company_id']);
        }

        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        // 查询总数
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM users u {$whereClause}");
        $stmt->execute($params);
        $total = $stmt->fetchColumn();
        
        // 查询数据
        $stmt = $this->conn->prepare("            SELECT u.id, u.username, u.mobile, u.sub_mobile, u.real_name, u.position, u.status, u.is_owner, 
                   u.permission, u.version, u.create_time, u.last_login_time,
                   c.id as company_id, c.name as company_name
            FROM users u
            LEFT JOIN companies c ON u.company_id = c.id
            {$whereClause}
            ORDER BY u.id DESC
            LIMIT :offset, :limit
        ");
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        
        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }

    /**
     * 获取超管和超管助理列表
     * @method GET
     * @route /user/adminList
     * 支持权限：superadmin, assistant
     */
    public function adminList(): void {
        $this->auth->checkAdmin();
        
        // 获取当前登录用户信息
        $currentUserId = $this->auth->getUserId();
        $stmt = $this->conn->prepare("SELECT permission FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $currentUserId]);
        $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(50, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = [];
        $params = [];
        
        // 基础条件：permission为superadmin或assistant的用户
        $where[] = "u.permission IN (:permission1, :permission2)";
        $params[':permission1'] = 'superadmin';
        $params[':permission2'] = 'assistant';
        
        // 筛选选项：用户名、真实姓名、手机号
        if (!empty($_GET['keyword'])) {
            $keyword = '%' . $_GET['keyword'] . '%';
            $where[] = "(u.username LIKE :keyword OR u.real_name LIKE :keyword OR u.mobile LIKE :keyword)";
            $params[':keyword'] = $keyword;
        }

        // 筛选选项：状态
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "u.status = :status";
            $params[':status'] = intval($_GET['status']);
        }

        // 筛选选项：所属公司
        if (isset($_GET['company_id']) && $_GET['company_id'] !== '' && $currentUser['permission'] === 'superadmin') {
            $where[] = "u.company_id = :company_id";
            $params[':company_id'] = intval($_GET['company_id']);
        }

        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        // 查询总数
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM users u {$whereClause}");
        $stmt->execute($params);
        $total = $stmt->fetchColumn();
        
        // 查询数据
        $stmt = $this->conn->prepare("            SELECT u.id, u.username, u.mobile, u.real_name, u.position, u.status, 
                   u.permission, u.create_time, u.last_login_time,
                   c.id as company_id, c.name as company_name
            FROM users u
            LEFT JOIN companies c ON u.company_id = c.id
            {$whereClause}
            ORDER BY u.id DESC
            LIMIT :offset, :limit
        ");
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        
        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }

    /**
     * 获取子账号列表
     * @method GET
     * @route /user/getSubAccountList
     */
    public function getSubAccountList(): void {
        $parentUserId = $this->auth->getUserId();
        if ($parentUserId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        // 获取当前用户的is_sub和company_id值
        $stmt = $this->conn->prepare("SELECT is_sub, company_id FROM users WHERE id = :id");
        $stmt->execute([':id' => $parentUserId]);
        $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        $currentUserIsSub = $currentUser['is_sub'] ?? 0;
        $currentUserCompanyId = $currentUser['company_id'] ?? null;
        
        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(50, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;
        
        // 构建查询条件
        $where = [];
        $params = [];
        
        // 根据当前用户的is_sub值决定查询条件
        if ($currentUserIsSub == 1) {
            // is_sub为1时，只显示当前用户的下级用户
            $where[] = "is_sub = 1 AND superior_id = :superior_id";
            $params[':superior_id'] = $parentUserId;
            
            // 确保是同一公司
            if ($currentUserCompanyId !== null) {
                $where[] = "company_id = :company_id";
                $params[':company_id'] = $currentUserCompanyId;
            } else {
                $where[] = "company_id IS NULL";
            }
        } else {
            // is_sub为0时，显示同一公司的所有用户
            if ($currentUserCompanyId !== null) {
                $where[] = "company_id = :company_id";
                $params[':company_id'] = $currentUserCompanyId;
            } else {
                $where[] = "company_id IS NULL";
            }
        }
        
        if (!empty($_GET['keyword'])) {
            $keyword = '%' . $_GET['keyword'] . '%';
            $where[] = "(username LIKE :keyword OR real_name LIKE :keyword)";
            $params[':keyword'] = $keyword;
        }
        
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "status = :status";
            $params[':status'] = intval($_GET['status']);
        }
        
        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';
        
        // 查询总数
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM users {$whereClause}");
        $stmt->execute($params);
        $total = $stmt->fetchColumn();
        
        // 查询数据
        $stmt = $this->conn->prepare(
            "
            SELECT id, username, real_name, position, permission as role, status, create_time, last_login_time, 
                   email, gender, basic_salary, sub_mobile, avatar, superior_id
            FROM users {$whereClause} 
            ORDER BY id DESC 
            LIMIT :offset, :limit
        ");
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        
        foreach ($params as $key => $value) {
            if ($key !== ':offset' && $key !== ':limit') {
                $stmt->bindValue($key, $value);
            }
        }
        
        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }

    /**
     * 更新子账号信息
     * @method POST
     * @route /user/updateSubAccount
     */
    public function updateSubAccount(): void {
        $parentUserId = $this->auth->getUserId();
        if ($parentUserId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['id'])) {
            throw new Exception("缺少子账号ID", 400);
        }
        
        // 检查子账号是否存在且属于当前用户
        $stmt = $this->conn->prepare(
            "
            SELECT id FROM users WHERE id = :id AND is_sub = 1 AND (parent_user_id = :parent_user_id OR superior_id = :superior_id) LIMIT 1
        "
        );
        $stmt->execute([':id' => $data['id'], ':parent_user_id' => $parentUserId, ':superior_id' => $parentUserId]);
        if (!$stmt->fetch()) {
            throw new Exception("子账号不存在或无权操作", 404);
        }
        
        // 构建更新字段
        $updateFields = [];
        $params = [':id' => $data['id']];
        
        // 更新用户名
        if (!empty($data['username'])) {
            // 检查用户名是否已被其他用户使用
            $stmt = $this->conn->prepare(
                "
                SELECT id FROM users WHERE username = :username AND id != :id LIMIT 1
            "
            );
            $stmt->execute([':username' => $data['username'], ':id' => $data['id']]);
            if ($stmt->fetch()) {
                throw new Exception("用户名已存在", 409);
            }
            
            $updateFields[] = "username = :username";
            $params[':username'] = $data['username'];
        }
        
        // 更新密码
        if (!empty($data['password'])) {
            $hashedPassword = Security::hashPassword($data['password']);
            $updateFields[] = "password = :password";
            $params[':password'] = $hashedPassword;
        }
        
        // 更新其他字段
        $optionalFields = ['real_name', 'position', 'permission', 'status'];
        foreach ($optionalFields as $field) {
            if (isset($data[$field])) {
                $updateFields[] = "{$field} = :{$field}";
                $params[":{$field}"] = $data[$field];
            }
        }
        
        if (empty($updateFields)) {
            throw new Exception("没有可更新的字段", 400);
        }
        
        // 执行更新
        $sql = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE id = :id";
        $stmt = $this->conn->prepare($sql);
        
        if (!$stmt->execute($params)) {
            throw new Exception("更新子账号信息失败", 500);
        }
        
        echo json_encode([
            'code' => 200,
            'msg' => '更新成功'
        ]);
    }

    /**
     * 删除子账号
     * @method POST
     * @route /user/deleteSubAccount
     */
    public function deleteSubAccount(): void {
        $parentUserId = $this->auth->getUserId();
        if ($parentUserId === 0) {
            throw new Exception("请先登录", 401);
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['id'])) {
            throw new Exception("缺少子账号ID", 400);
        }
        
        // 检查子账号是否存在且属于当前用户
        $stmt = $this->conn->prepare(
            "
            SELECT id FROM users WHERE id = :id AND is_sub = 1 AND (parent_user_id = :parent_user_id OR superior_id = :superior_id) LIMIT 1
        "
        );
        $stmt->execute([':id' => $data['id'], ':parent_user_id' => $parentUserId, ':superior_id' => $parentUserId]);
        if (!$stmt->fetch()) {
            throw new Exception("子账号不存在或无权操作", 404);
        }
        
        // 执行删除
        $stmt = $this->conn->prepare("DELETE FROM users WHERE id = :id");
        
        if (!$stmt->execute([':id' => $data['id']])) {
            throw new Exception("删除子账号失败", 500);
        }
        
        echo json_encode([
            'code' => 200,
            'msg' => '删除成功'
        ]);
    }

    /**
     * 用户注册
     * @method POST
     * @route /user/register
     */
    public function register(): void {
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        $requiredFields = ['username', 'password', 'mobile'];
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                throw new Exception("缺少必填字段: {$field}", 400);
            }
        }

        // 验证用户名格式
        if (!preg_match('/^[a-zA-Z0-9_\x{4e00}-\x{9fa5}]{2,20}$/u', $data['username'])) {
            throw new Exception("用户名只能包含中文、字母、数字和下划线，长度2-20位", 400);
        }

        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $data['mobile'])) {
            throw new Exception("手机号格式不正确", 400);
        }

        // 检查用户名是否已存在
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE username = :username LIMIT 1");
        $stmt->execute([':username' => $data['username']]);
        if ($stmt->fetch()) {
            throw new Exception("用户名已存在", 409);
        }

        // 检查手机号是否已注册
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE mobile = :mobile LIMIT 1");
        $stmt->execute([':mobile' => $data['mobile']]);
        if ($stmt->fetch()) {
            throw new Exception("手机号已注册", 409);
        }

        // 密码哈希处理
        $hashedPassword = Security::hashPassword($data['password']);

        // 生成用户数据
        $userData = [
            ':username' => $data['username'],
            ':password' => $hashedPassword,
            ':mobile' => $data['mobile'],
            ':real_name' => $data['real_name'] ?? '',
            ':position' => $data['position'] ?? '',
            ':permission' => 'member', // 新注册用户默认为普通成员
            ':company_id' => $data['company_id'] ?? null,
            ':create_time' => time(),
            ':last_login_time' => 0,
            ':wx_openid' => $data['wx_openid'] ?? null,
            ':wx_unionid' => $data['wx_unionid'] ?? null,
            ':version' => 1, // 默认个人版
            // 生成唯一的sub_mobile值，避免空值重复
            ':sub_mobile' => 'main_' . time() . '_' . rand(1000, 9999)
        ];

        // 插入用户数据
        $stmt = $this->conn->prepare("
            INSERT INTO users (
                username, password, mobile, real_name, position, permission, company_id,
                create_time, last_login_time, wx_openid, wx_unionid, version, sub_mobile
            ) VALUES (
                :username, :password, :mobile, :real_name, :position, :permission, :company_id,
                :create_time, :last_login_time, :wx_openid, :wx_unionid, :version, :sub_mobile
            )
        ");

        if (!$stmt->execute($userData)) {
            throw new Exception("注册失败，请稍后再试", 500);
        }

        $userId = $this->conn->lastInsertId();

        // 返回注册成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '注册成功',
            'data' => [
                'user_id' => $userId
            ]
        ]);
    }

    /**
     * 用户登录
     * @method POST
     * @route /user/login
     */
    public function login(): void {
        try {
            $data = json_decode(file_get_contents('php://input'), true);
            
            // 验证必填字段
            if (empty($data['username']) || empty($data['password'])) {
                throw new Exception("请输入用户名和密码", 400);
            }

            // 查询用户信息
            $username = $data['username'];
            $user = null;
            
            // 先判断username是否符合手机号格式
            if (preg_match('/^1[3-9]\d{9}$/', $username)) {
                // 符合手机号格式，先在mobile字段查找
                $stmt = $this->conn->prepare(
                    "
                    SELECT u.id, u.username, u.password, u.mobile, u.sub_mobile, u.real_name, u.position, u.status, u.is_owner, 
                           u.permission, u.token, u.token_expire, u.version, u.is_sub, u.parent_user_id,
                           c.id as company_id, c.name as company_name
                    FROM users u
                    LEFT JOIN companies c ON u.company_id = c.id
                    WHERE u.mobile = :mobile
                    LIMIT 1
                ");
                $stmt->execute([':mobile' => $username]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
            }
            
            // 如果没找到用户，或者username不符合手机号格式，在username字段查找
            if (!$user) {
                $stmt = $this->conn->prepare(
                    "
                    SELECT u.id, u.username, u.password, u.mobile, u.sub_mobile, u.real_name, u.position, u.status, u.is_owner, 
                           u.permission, u.token, u.token_expire, u.version, u.is_sub, u.parent_user_id,
                           c.id as company_id, c.name as company_name
                    FROM users u
                    LEFT JOIN companies c ON u.company_id = c.id
                    WHERE u.username = :username
                    LIMIT 1
                ");
                $stmt->execute([':username' => $username]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
            }

            if (!$user) {
                throw new Exception("用户名或密码错误", 400);
            }

            // 验证密码
            if (!Security::verifyPassword($data['password'], $user['password'])) {
                throw new Exception("用户名或密码错误", 400);
            }

            // 检查是否是后台账号
            if (in_array($user['permission'], ['superadmin', 'assistant'])) {
                throw new Exception("这是后台账号，请使用前台账号登录", 400);
            }

            // 检查用户状态
            if ($user['status'] != 1) {
                throw new Exception("账号已被禁用，请联系管理员", 400);
            }

            // 子账号登录特殊处理
            if (isset($data['is_sub_account']) && $data['is_sub_account']) {
                // 检查是否是子账号
                if ($user['is_sub'] != 1) {
                    throw new Exception("该账号不是子账号", 400);
                }
                
                // 验证主账号手机号
                if (empty($data['parent_mobile'])) {
                    throw new Exception("子账号登录请输入主账号手机号", 400);
                }
                
                // 验证手机号格式
                if (!preg_match('/^1[3-9]\d{9}$/', $data['parent_mobile'])) {
                    throw new Exception("请输入正确的手机号格式", 400);
                }
                
                // 查询主账号信息，验证手机号与子账号的关系
                $stmt = $this->conn->prepare(
                    "
                    SELECT id FROM users 
                    WHERE mobile = :parent_mobile AND id = :parent_user_id
                    LIMIT 1
                "
                );
                $stmt->execute([
                    ':parent_mobile' => $data['parent_mobile'],
                    ':parent_user_id' => $user['parent_user_id']
                ]);
                
                if (!$stmt->fetch()) {
                    // 主账号手机号与子账号不匹配时，保持HTTP状态码为200，只在JSON响应中设置code为401
                    echo json_encode([
                        'code' => 401,
                        'msg' => '主账号手机号与子账号不匹配'
                    ]);
                    return;
                }
            } else {
                // 主账号登录，确保不是子账号
                if ($user['is_sub'] == 1) {
                    echo json_encode([
                        'code' => 401,
                        'msg' => '子账号请使用子账号登录方式'
                    ]);
                    return;
                }
            }

            // 检查现有token是否有效
            $token = $user['token'];
            $tokenExpire = time() + TOKEN_EXPIRE;
            
            // 如果现有token已过期或不存在，则生成新token
            if (empty($user['token']) || $user['token_expire'] < time()) {
                $token = Security::generateToken($user['id']);
                
                // 更新用户Token和最后登录时间（包括新生成的token）
                $stmt = $this->conn->prepare("
                    UPDATE users
                    SET 
                        token = :token,
                        token_expire = :token_expire,
                        last_login_time = :last_login_time
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':token' => $token,
                    ':token_expire' => $tokenExpire,
                    ':last_login_time' => time(),
                    ':id' => $user['id']
                ]);
            } else {
                // 只更新token过期时间和最后登录时间（保留现有有效token）
                $stmt = $this->conn->prepare("
                    UPDATE users
                    SET 
                        token_expire = :token_expire,
                        last_login_time = :last_login_time
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':token_expire' => $tokenExpire,
                    ':last_login_time' => time(),
                    ':id' => $user['id']
                ]);
            }

            // 返回登录成功信息和完整用户信息
            echo json_encode([
                'code' => 200,
                'msg' => '登录成功',
                'data' => [
                    'token' => $token,
                    'token_expire' => $tokenExpire,
                    'user_info' => [
                        'id' => $user['id'],
                        'username' => $user['username'],
                        'mobile' => $user['mobile'],
                        'sub_mobile' => $user['sub_mobile'],
                        'real_name' => $user['real_name'],
                        'position' => $user['position'],
                        'permission' => $user['permission'],
                        'version' => $user['version'],
                        'company_id' => $user['company_id'],
                        'is_owner' => $user['is_owner'],
                        'is_sub' => $user['is_sub'],
                        'company_name' => $user['company_name'],
                        'company' => [
                            'id' => $user['company_id'],
                            'name' => $user['company_name']
                        ]
                    ]
                ]
            ]);

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取用户信息
     * @method GET
     * @route /user/info
     */
    public function info(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $stmt = $this->conn->prepare(
            "
            SELECT u.id, u.username, u.mobile, u.sub_mobile, u.real_name, u.position, u.create_time, u.avatar, u.is_owner, 
                   u.last_login_time, u.permission, u.version, u.is_sub, u.parent_user_id,
                   c.id as company_id, c.name as company_name
            FROM users u
            LEFT JOIN companies c ON u.company_id = c.id
            WHERE u.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            throw new Exception("用户不存在", 404);
        }

        // 统一返回用户信息，通过is_sub字段区分子账号和主账号
        echo json_encode([
            'code' => 200,
            'data' => $user
        ]);
    }

    /**
     * 修改用户密码
     * @method POST
     * @route /user/changePass
     */
    public function changePass(): void {
        $userId = $this->auth->getUserId();
        if ($userId === 0) {
            throw new Exception("请先登录", 401);
        }

        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        $requiredFields = ['old_password', 'new_password'];
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                throw new Exception("缺少必填字段: {$field}", 400);
            }
        }

        // 查询当前用户密码
        $stmt = $this->conn->prepare("SELECT password FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            throw new Exception("用户不存在", 404);
        }

        // 验证旧密码
        if (!Security::verifyPassword($data['old_password'], $user['password'])) {
            throw new Exception("旧密码不正确", 400);
        }

        // 新密码不能与旧密码相同
        if (Security::verifyPassword($data['new_password'], $user['password'])) {
            throw new Exception("新密码不能与旧密码相同", 400);
        }

        // 生成新密码哈希
        $newHashedPassword = Security::hashPassword($data['new_password']);

        // 更新密码并使旧Token失效
        $stmt = $this->conn->prepare("
            UPDATE users
            SET 
                password = :password,
                token = NULL,
                token_expire = NULL
            WHERE id = :id
        ");
        $stmt->execute([
            ':password' => $newHashedPassword,
            ':id' => $userId
        ]);

        // 返回成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '密码修改成功，请重新登录'
        ]);
    }

    /**
     * 获取用户列表 (需要管理员权限)
     * @method GET
     * @route /user/list
     */
    public function list(): void {
        $this->auth->checkAdmin();
        
        // 获取当前登录用户信息
        $currentUserId = $this->auth->getUserId();
        $stmt = $this->conn->prepare("SELECT permission, position, company_id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $currentUserId]);
        $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(50, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = [];
        $params = [];
        
        // 根据当前用户权限进行过滤
        if ($currentUser['permission'] !== 'superadmin') {
            // 非超级管理员只能查看同一公司的用户
            if ($currentUser['company_id'] === null) {
                // 处理company_id为null的情况
                $where[] = "u.company_id IS NULL";
            } else {
                $where[] = "u.company_id = :current_company_id";
                $params[':current_company_id'] = $currentUser['company_id'];
            }
            
            // 根据职位进行过滤
            if ($currentUser['permission'] === 'admin') {
                if ($currentUser['position'] === '拍摄主管') {
                    $where[] = "u.position IN (:position1, :position2)";
                    $params[':position1'] = '摄影师';
                    $params[':position2'] = '录像师';
                } else if ($currentUser['position'] === '后期主管') {
                    $where[] = "u.position IN (:position1, :position2)";
                    $params[':position1'] = '照片修图师';
                    $params[':position2'] = '视频剪辑师';
                } else if ($currentUser['position'] === '市场主管') {
                    $where[] = "u.position IN (:position1, :position2, :position3)";
                    $params[':position1'] = '市场运营';
                    $params[':position2'] = '市场销售';
                    $params[':position3'] = '售后客服';
                } else {
                    // 其他管理员只能查看普通用户
                    $where[] = "u.permission = 'member'";
                }
            } else {
                // 普通用户只能查看自己
                $where[] = "u.id = :current_user_id";
                $params[':current_user_id'] = $currentUserId;
            }
        }
        
        // 额外的过滤条件
        if (!empty($_GET['keyword'])) {
            $keyword = '%' . $_GET['keyword'] . '%';
            $where[] = "(u.username LIKE :keyword OR u.real_name LIKE :keyword OR u.mobile LIKE :keyword)";
            $params[':keyword'] = $keyword;
        }

        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "u.status = :status";
            $params[':status'] = intval($_GET['status']);
        }

        // 新增：根据permission参数过滤权限类型
        if (isset($_GET['permission']) && $_GET['permission'] !== '') {
            $permission = strtolower($_GET['permission']);
            
            if ($permission === 'member') {
                $where[] = "u.permission = 'member'";
            } elseif ($permission === 'admin') {
                // 对于superadmin，可以查看所有管理员类型
                if ($currentUser['permission'] === 'superadmin') {
                    $where[] = "u.permission IN ('admin', 'superadmin')";
                } else {
                    // 非superadmin只能查看admin类型
                    $where[] = "u.permission = 'admin'";
                }
            }
        }

        if (isset($_GET['company_id']) && $_GET['company_id'] !== '' && $currentUser['permission'] === 'superadmin') {
            $where[] = "u.company_id = :company_id";
            $params[':company_id'] = intval($_GET['company_id']);
        }

        // 新增：根据version参数过滤版本类型
        if (isset($_GET['version']) && $_GET['version'] !== '') {
            $where[] = "u.version = :version";
            $params[':version'] = intval($_GET['version']);
        }
        
        // 新增：根据adminType参数过滤版本类型
        if (isset($_GET['adminType']) && $_GET['adminType'] !== '') {
            $adminType = strtolower($_GET['adminType']);
            $versionMap = [
                'personal' => 1,    // 个人版
                'business' => 2,    // 商级版/高级版
                'team' => 3,        // 团队版
                'enterprise' => 4   // 企业版
            ];
            
            if (isset($versionMap[$adminType])) {
                $where[] = "u.version = :admin_type_version";
                $params[':admin_type_version'] = $versionMap[$adminType];
            }
        }
        
        // 新增：根据is_sub参数过滤主账号/子账号
        if (isset($_GET['is_sub']) && $_GET['is_sub'] !== '') {
            $where[] = "u.is_sub = :is_sub";
            $params[':is_sub'] = intval($_GET['is_sub']);
        }

        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        // 查询总数
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM users u {$whereClause}");
        $stmt->execute($params);
        $total = $stmt->fetchColumn();
        
        // 可选：记录关键操作到错误日志（可根据需要启用）
        // error_log("User::list - Total count: " . $total);

        // 查询数据
        $stmt = $this->conn->prepare("            SELECT u.id, u.username, u.mobile, u.sub_mobile, u.real_name, u.position, u.status, u.is_owner, 
                   u.permission, u.version, u.create_time, u.last_login_time,
                   c.id as company_id, c.name as company_name
            FROM users u
            LEFT JOIN companies c ON u.company_id = c.id
            {$whereClause}
            ORDER BY u.id DESC
            LIMIT :offset, :limit
        ");
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        
        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }

    /**
     * 创建用户 (需要管理员权限)
     * @method POST
     * @route /user/create
     */
    public function create(): void {
        $this->auth->checkAdmin();
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        $requiredFields = ['username', 'password', 'mobile'];
        foreach ($requiredFields as $field) {
            if (empty($data[$field])) {
                throw new Exception("缺少必填字段: {$field}", 400);
            }
        }

        // 验证用户名格式
        if (!preg_match('/^[a-zA-Z0-9_\x{4e00}-\x{9fa5}]{2,20}$/u', $data['username'])) {
            throw new Exception("用户名只能包含中文、字母、数字和下划线，长度2-20位", 400);
        }

        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $data['mobile'])) {
            throw new Exception("手机号格式不正确", 400);
        }

        // 检查用户名是否已存在
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE username = :username LIMIT 1");
        $stmt->execute([':username' => $data['username']]);
        if ($stmt->fetch()) {
            throw new Exception("用户名已存在", 409);
        }

        // 检查手机号是否已注册
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE mobile = :mobile LIMIT 1");
        $stmt->execute([':mobile' => $data['mobile']]);
        if ($stmt->fetch()) {
            throw new Exception("手机号已注册", 409);
        }

        // 检查公司是否存在
        if (!empty($data['company_id'])) {
            $stmt = $this->conn->prepare("SELECT id FROM companies WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $data['company_id']]);
            if (!$stmt->fetch()) {
                throw new Exception("公司不存在", 404);
            }
        }

        // 密码哈希处理
        $hashedPassword = Security::hashPassword($data['password']);

        // 设置权限（管理员只能创建普通用户，超级管理员可以创建管理员）
        $currentPermission = $this->auth->getPermission();
        $userPermission = 'member';
        
        if ($currentPermission === 'superadmin' && isset($data['permission'])) {
            if (in_array($data['permission'], ['member', 'admin', 'superadmin'])) {
                $userPermission = $data['permission'];
            }
        }

        // 设置版本类型
        $version = 1; // 默认个人版
        if ($currentPermission === 'superadmin' && isset($data['version'])) {
            if (in_array($data['version'], [1, 2, 3, 4])) {
                $version = $data['version'];
            }
        }

        // 生成用户数据
        $userData = [
            ':username' => $data['username'],
            ':password' => $hashedPassword,
            ':mobile' => $data['mobile'],
            ':real_name' => $data['real_name'] ?? '',
            ':position' => $data['position'] ?? '',
            ':permission' => $userPermission,
            ':version' => $version,
            ':company_id' => (!empty($data['company_id']) && $data['company_id'] !== '') ? intval($data['company_id']) : null,
            ':status' => $data['status'] ?? 1,
            ':is_owner' => $data['is_owner'] ?? 0,
            ':create_time' => time(),
            ':last_login_time' => 0,
            ':wx_openid' => $data['wx_openid'] ?? null,
            ':wx_unionid' => $data['wx_unionid'] ?? null,
            // 生成唯一的sub_mobile值，避免空值重复
            ':sub_mobile' => 'admin_create_' . time() . '_' . rand(1000, 9999)
        ];

        // 插入用户数据
        $stmt = $this->conn->prepare("
            INSERT INTO users (
                username, password, mobile, real_name, position, permission, version, company_id, status,is_owner,
                create_time, last_login_time, wx_openid, wx_unionid, sub_mobile
            ) VALUES (
                :username, :password, :mobile, :real_name, :position, :permission, :version, :company_id, :status,:is_owner,
                :create_time, :last_login_time, :wx_openid, :wx_unionid, :sub_mobile
            )
        ");

        if (!$stmt->execute($userData)) {
            throw new Exception("创建用户失败，请稍后再试", 500);
        }

        $userId = $this->conn->lastInsertId();

        // 返回创建成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '创建成功',
            'data' => [
                'user_id' => $userId,
                'permission' => $userPermission,
                'version' => $version
            ]
        ]);
    }

    /**
     * 更新用户信息
     * @method POST
     * @route /user/update
     */
    public function update(): void {
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 判断是管理员更新还是用户自己更新
        if (isset($data['id']) && !empty($data['id'])) {
            // 管理员更新 - 需要管理员权限
            $this->auth->checkAdmin();
            $userId = $data['id'];
        } else {
            // 用户自己更新 - 通过token获取用户ID
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }
        }

        // 检查用户是否存在
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $userId]);
        if (!$stmt->fetch()) {
            throw new Exception("用户不存在", 404);
        }

        // 构建更新字段
        $updateFields = [];
        $params = [':id' => $userId];

        // 更新密码 - 只有用户自己可以更新密码
        if (!empty($data['password'])) {
            // 如果是管理员操作且不是自己更新，不允许修改密码
            if (isset($data['id']) && $data['id'] != $this->auth->getUserId()) {
                throw new Exception("管理员不能直接修改其他用户密码", 400);
            }

            // 如果是用户自己修改密码，需要验证旧密码
            if (!isset($data['id']) && empty($data['old_password'])) {
                throw new Exception("修改密码需要提供旧密码", 400);
            }

            // 验证用户自己修改密码时的旧密码
            if (!isset($data['id'])) {
                $stmt = $this->conn->prepare("SELECT password FROM users WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $userId]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!Security::verifyPassword($data['old_password'], $user['password'])) {
                    throw new Exception("旧密码不正确", 400);
                }
            }

            $updateFields[] = "password = :password";
            $params[':password'] = Security::hashPassword($data['password']);
            
            // 密码修改后使token失效
            $updateFields[] = "token = NULL";
            $updateFields[] = "token_expire = NULL";
        }

        // 更新手机号
        if (!empty($data['mobile'])) {
            if (!preg_match('/^1[3-9]\d{9}$/', $data['mobile'])) {
                throw new Exception("手机号格式不正确", 400);
            }
            
            // 检查手机号是否已被其他用户使用
            $stmt = $this->conn->prepare("SELECT id FROM users WHERE mobile = :mobile AND id != :id LIMIT 1");
            $stmt->execute([':mobile' => $data['mobile'], ':id' => $userId]);
            if ($stmt->fetch()) {
                throw new Exception("手机号已被其他用户使用", 409);
            }
            
            $updateFields[] = "mobile = :mobile";
            $params[':mobile'] = $data['mobile'];
        }

        // 更新其他字段
        $optionalFields = ['real_name', 'position', 'email'];
        
        // 超级管理员和管理员都可以更新子账号的permission字段
        if (($this->auth->getPermission() === 'superadmin' || $this->auth->getPermission() === 'admin') && isset($data['permission'])) {
            $optionalFields[] = 'permission';
        }
        
        // 只有超级管理员可以更新company_id字段
        if ($this->auth->getPermission() === 'superadmin' && isset($data['company_id'])) {
            // 检查公司是否存在
            if (!empty($data['company_id'])) {
                $stmt = $this->conn->prepare("SELECT id FROM companies WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $data['company_id']]);
                if (!$stmt->fetch()) {
                    throw new Exception("公司不存在", 404);
                }
            }
            $optionalFields[] = 'company_id';
        }
        
        // 只有管理员可以更新status字段
        if ($this->auth->getPermission() !== 'member' && isset($data['status'])) {
            $optionalFields[] = 'status';
        }

        // 只有超级管理员可以更新version字段
        if ($this->auth->getPermission() === 'superadmin' && isset($data['version'])) {
            if (in_array($data['version'], [1, 2, 3, 4])) {
                $optionalFields[] = 'version';
            }
        }
        
        // 只有超级管理员和管理员可以更新superior_id字段（分配员工给管理员）
        if (($this->auth->getPermission() === 'superadmin' || $this->auth->getPermission() === 'admin') && isset($data['superior_id'])) {
            // 验证superior_id对应的用户存在且是管理员
            if (!empty($data['superior_id'])) {
                $stmt = $this->conn->prepare("SELECT id FROM users WHERE id = :id AND permission = 'admin' LIMIT 1");
                $stmt->execute([':id' => $data['superior_id']]);
                if (!$stmt->fetch()) {
                    throw new Exception("指定的管理员不存在", 404);
                }
            }
            $optionalFields[] = 'superior_id';
        }

        foreach ($optionalFields as $field) {
            if (isset($data[$field])) {
                $updateFields[] = "{$field} = :{$field}";
                $params[":{$field}"] = $data[$field];
            }
        }

        if (empty($updateFields)) {
            throw new Exception("没有可更新的字段", 400);
        }

        // 执行更新
        $sql = "UPDATE users SET " . implode(', ', $updateFields) . " WHERE id = :id";
        $stmt = $this->conn->prepare($sql);
        
        if (!$stmt->execute($params)) {
            throw new Exception("更新用户信息失败", 500);
        }

        // 返回成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '更新成功'
        ]);
    }

    /**
     * 获取用户详情 (需要管理员权限)
     * @method GET
     * @route /user/detail
     */
    public function detail(): void {
        $this->auth->checkAdmin();
        
        if (empty($_GET['id'])) {
            throw new Exception("缺少用户ID", 400);
        }
        
        $userId = intval($_GET['id']);
        
        $stmt = $this->conn->prepare(" 
            SELECT u.id, u.username, u.mobile, u.sub_mobile, u.real_name, u.position, u.status, 
                   u.permission, u.version, u.create_time, u.last_login_time, 
                   c.id as company_id, c.name as company_name
            FROM users u
            LEFT JOIN companies c ON u.company_id = c.id
            WHERE u.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            throw new Exception("用户不存在", 404);
        }
        
        // 返回用户详情
        echo json_encode([
            'code' => 200,
            'data' => $user
        ]);
    }
    
    /**
     * 删除用户 (需要管理员权限)
     * @method POST
     * @route /user/delete
     */
    public function delete(): void {
        $this->auth->checkAdmin();
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['id'])) {
            throw new Exception("缺少用户ID", 400);
        }

        // 检查用户是否存在
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $data['id']]);
        if (!$stmt->fetch()) {
            throw new Exception("用户不存在", 404);
        }

        // 执行删除 (实际项目中可能采用软删除)
        $stmt = $this->conn->prepare("DELETE FROM users WHERE id = :id");
        
        if (!$stmt->execute([':id' => $data['id']])) {
            throw new Exception("删除用户失败", 500);
        }

        // 返回成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '删除成功'
        ]);
    }

    /**
     * 微信一键登录
     * @method POST
     * @route /user/wxlogin
     */
    public function wxlogin(): void {
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['code'])) {
            throw new Exception("缺少微信授权code", 400);
        }

        // 这里应该调用微信API获取openid和unionid
        // 以下是模拟代码，实际项目中需要替换为真实的微信API调用
        $wxInfo = $this->getWechatUserInfo($data['code']);
        
        if (!$wxInfo || empty($wxInfo['openid'])) {
            throw new Exception("微信登录失败，请重试", 400);
        }

        // 检查是否已绑定用户
        $stmt = $this->conn->prepare("
            SELECT id, username, company, mobile, real_name, position, status, permission, version
            FROM users
            WHERE wx_openid = :openid OR wx_unionid = :unionid
            LIMIT 1
        ");
        $stmt->execute([
            ':openid' => $wxInfo['openid'],
            ':unionid' => $wxInfo['unionid'] ?? null
        ]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // 如果用户不存在且配置了自动注册
        if (!$user && ($data['auto_register'] ?? false)) {
            // 自动注册用户
            $username = 'wx_' . substr(md5($wxInfo['openid']), 0, 12);
            $password = bin2hex(random_bytes(8));
            
            $userData = [
                ':username' => $username,
                ':password' => Security::hashPassword($password),
                ':mobile' => '',
                ':real_name' => $wxInfo['company'] ?? '',
                ':position' => '',
                ':permission' => 'member',
                ':version' => 1, // 默认个人版
                ':wx_openid' => $wxInfo['openid'],
                ':wx_unionid' => $wxInfo['unionid'] ?? null,
                ':create_time' => time(),
                ':last_login_time' => 0,
                // 生成唯一的sub_mobile值，避免空值重复
                ':sub_mobile' => 'wx_auto_' . time() . '_' . rand(1000, 9999)
            ];

            $stmt = $this->conn->prepare("
                INSERT INTO users (
                    username, password, mobile, real_name, position, permission, version,
                    wx_openid, wx_unionid, create_time, last_login_time, sub_mobile
                ) VALUES (
                    :username, :password, :mobile, :real_name, :position, :permission, :version,
                    :wx_openid, :wx_unionid, :create_time, :last_login_time, :sub_mobile
                )
            ");
            
            if (!$stmt->execute($userData)) {
                throw new Exception("自动注册失败", 500);
            }
            
            $userId = $this->conn->lastInsertId();
            
            // 重新查询用户信息
            $stmt = $this->conn->prepare("
                SELECT id, username, company, mobile, real_name, position, status, permission, version
                FROM users
                WHERE id = :id
                LIMIT 1
            ");
            $stmt->execute([':id' => $userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
        }

        if (!$user) {
            throw new Exception("未绑定微信账号，请先绑定或注册", 400);
        }

        // 检查用户状态
        if ($user['status'] != 1) {
            throw new Exception("账号已被禁用，请联系管理员", 400);
        }

        // 生成新Token
        $token = Security::generateToken($user['id']);
        $tokenExpire = time() + TOKEN_EXPIRE;

        // 更新用户Token和最后登录时间
        $stmt = $this->conn->prepare("
            UPDATE users
            SET 
                token = :token,
                token_expire = :token_expire,
                last_login_time = :last_login_time
            WHERE id = :id
        ");
        $stmt->execute([
            ':token' => $token,
            ':token_expire' => $tokenExpire,
            ':last_login_time' => time(),
            ':id' => $user['id']
        ]);

        // 返回登录成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'token_expire' => $tokenExpire,
                'user_info' => [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'company' => $user['company'],
                    'mobile' => $user['mobile'],
                    'real_name' => $user['real_name'],
                    'position' => $user['position'],
                    'permission' => $user['permission'],
                    'version' => $user['version']
                ]
            ]
        ]);
    }

    /**
     * 手机验证码登录
     * @method POST
     * @route /user/smslogin
     */
    public function smslogin(): void {
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['mobile']) || empty($data['code'])) {
            throw new Exception("缺少手机号或验证码", 400);
        }

        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $data['mobile'])) {
            throw new Exception("手机号格式不正确", 400);
        }

        // 这里应该验证短信验证码
        // 以下是模拟代码，实际项目中需要替换为真实的短信验证码验证
        if (!$this->verifySmsCode($data['mobile'], $data['code'])) {
            throw new Exception("验证码错误或已过期", 400);
        }

        // 查询用户信息
        $stmt = $this->conn->prepare("
            SELECT id, username, company, mobile, real_name, position, status, permission, version
            FROM users
            WHERE mobile = :mobile
            LIMIT 1
        ");
        $stmt->execute([':mobile' => $data['mobile']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // 如果用户不存在且配置了自动注册
        if (!$user && ($data['auto_register'] ?? false)) {
            // 自动注册用户
            $username = 'sms_' . substr($data['mobile'], -4) . '_' . substr(md5(time()), 0, 4);
            $password = bin2hex(random_bytes(8));
            
            $userData = [
                ':username' => $username,
                ':password' => Security::hashPassword($password),
                ':mobile' => $data['mobile'],
                ':real_name' => '',
                ':position' => '',
                ':permission' => 'member',
                ':version' => 1, // 默认个人版
                ':create_time' => time(),
                ':last_login_time' => 0,
                // 生成唯一的sub_mobile值，避免空值重复
                ':sub_mobile' => 'sms_auto_' . time() . '_' . rand(1000, 9999)
            ];

            $stmt = $this->conn->prepare("
                INSERT INTO users (
                    username, password, mobile, real_name, position, permission, version,
                    create_time, last_login_time, sub_mobile
                ) VALUES (
                    :username, :password, :mobile, :real_name, :position, :permission, :version,
                    :create_time, :last_login_time, :sub_mobile
                )
            ");
            
            if (!$stmt->execute($userData)) {
                throw new Exception("自动注册失败", 500);
            }
            
            $userId = $this->conn->lastInsertId();
            
            // 重新查询用户信息
            $stmt = $this->conn->prepare("
                SELECT id, username, company, mobile, real_name, position, status, permission, version
                FROM users
                WHERE id = :id
                LIMIT 1
            ");
            $stmt->execute([':id' => $userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
        }

        if (!$user) {
            throw new Exception("手机号未注册", 400);
        }

        // 检查用户状态
        if ($user['status'] != 1) {
            throw new Exception("账号已被禁用，请联系管理员", 400);
        }

        // 生成新Token
        $token = Security::generateToken($user['id']);
        $tokenExpire = time() + TOKEN_EXPIRE;

        // 更新用户Token和最后登录时间
        $stmt = $this->conn->prepare("
            UPDATE users
            SET 
                token = :token,
                token_expire = :token_expire,
                last_login_time = :last_login_time
            WHERE id = :id
        ");
        $stmt->execute([
            ':token' => $token,
            ':token_expire' => $tokenExpire,
            ':last_login_time' => time(),
            ':id' => $user['id']
        ]);

        // 返回登录成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'token_expire' => $tokenExpire,
                'user_info' => [
                    'id' => $user['id'],
                    'username' => $user['username'],
                    'company' => $user['company'],
                    'mobile' => $user['mobile'],
                    'real_name' => $user['real_name'],
                    'position' => $user['position'],
                    'permission' => $user['permission'],
                    'version' => $user['version']
                ]
            ]
        ]);
    }

    /**
     * 获取首页数据
     * @method GET
     * @route /user/indexData
     */
    public function indexData(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            // 获取用户基本信息 - 修改这里的查询语句
            $stmt = $this->conn->prepare("
                SELECT 
                    u.id, 
                    u.username, 
                    u.real_name, 
                    u.company_id, 
                    c.name as company_name,
                    u.permission,
                    u.version
                FROM users u
                LEFT JOIN companies c ON u.company_id = c.id
                WHERE u.id = :id 
                LIMIT 1
            ");
            $stmt->execute([':id' => $userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                throw new Exception("用户不存在", 404);
            }

            $today = date('Y-m-d');
            $tomorrow = date('Y-m-d', strtotime('+1 day'));
            $dayAfterTomorrow = date('Y-m-d', strtotime('+2 days'));

            // 查询今日订单统计（以开始日期为准）
            $stmt = $this->conn->prepare("
                SELECT 
                    COUNT(*) as order_count,
                    COALESCE(SUM(CAST(total_amount AS DECIMAL(10,2))), 0) as total_amount,
                    COALESCE(SUM(CAST(deposit AS DECIMAL(10,2))), 0) as total_deposit
                FROM orders
                WHERE creator_id = :creator_id 
                AND start_date = :today
            ");
            $stmt->execute([
                ':creator_id' => (int)$userId,
                ':today' => $today
            ]);
            $todayStats = $stmt->fetch(PDO::FETCH_ASSOC);

            // 确保数值字段是数字类型
            $orderCount = isset($todayStats['order_count']) ? (int)$todayStats['order_count'] : 0;
            $totalAmount = isset($todayStats['total_amount']) ? floatval($todayStats['total_amount']) : 0.0;
            $totalDeposit = isset($todayStats['total_deposit']) ? floatval($todayStats['total_deposit']) : 0.0;

            // 查询今日任务数（开始日期<=今天<=结束日期的订单）
            $stmt = $this->conn->prepare("
                SELECT COUNT(*) as task_count
                FROM orders
                WHERE creator_id = :creator_id 
                AND start_date <= :today 
                AND end_date >= :today
            ");
            $stmt->execute([
                ':creator_id' => (int)$userId,
                ':today' => $today
            ]);
            $todayTaskCount = (int)$stmt->fetchColumn();

            // 查询明日任务数
            $stmt = $this->conn->prepare("
                SELECT COUNT(*) as task_count
                FROM orders
                WHERE creator_id = :creator_id 
                AND start_date <= :tomorrow 
                AND end_date >= :tomorrow
            ");
            $stmt->execute([
                ':creator_id' => (int)$userId,
                ':tomorrow' => $tomorrow
            ]);
            $tomorrowTaskCount = (int)$stmt->fetchColumn();

            // 查询后日任务数
            $stmt = $this->conn->prepare("
                SELECT COUNT(*) as task_count
                FROM orders
                WHERE creator_id = :creator_id 
                AND start_date <= :day_after_tomorrow 
                AND end_date >= :day_after_tomorrow
            ");
            $stmt->execute([
                ':creator_id' => (int)$userId,
                ':day_after_tomorrow' => $dayAfterTomorrow
            ]);
            $dayAfterTomorrowTaskCount = (int)$stmt->fetchColumn();

            // 返回首页数据 - 更新返回数据结构中的company字段
            echo json_encode([
                'code' => 200,
                'data' => [
                    'user_info' => [
                        'username' => $user['username'] ?? '',
                        'real_name' => $user['real_name'] ?? '',
                        'company' => [
                            'id' => $user['company_id'] ?? null,
                            'name' => $user['company_name'] ?? ''
                        ],
                        'permission' => $user['permission'] ?? 'member',
                        'version' => $user['version'] ?? 1
                    ],
                    'today_stats' => [
                        'order_count' => $orderCount,
                        'total_amount' => $totalAmount,
                        'total_deposit' => $totalDeposit
                    ],
                    'task_stats' => [
                        'today' => $todayTaskCount,
                        'tomorrow' => $tomorrowTaskCount,
                        'day_after_tomorrow' => $dayAfterTomorrowTaskCount
                    ],
                    'date_info' => [
                        'today' => $today,
                        'tomorrow' => $tomorrow,
                        'day_after_tomorrow' => $dayAfterTomorrow
                    ]
                ]
            ]);

        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'message' => $e->getMessage()
            ]);
        }
    }

    /**
     * 上传用户头像
     * @method POST
     * @route /user/uploadAvatar
     */
    public function uploadAvatar(): void {
        try {
            $userId = $this->auth->getUserId();
            if ($userId === 0) {
                throw new Exception("请先登录", 401);
            }

            if (empty($_FILES['file'])) {
                throw new Exception("请选择上传文件", 400);
            }

            $file = $_FILES['file'];
            
            // 验证文件上传是否成功
            if ($file['error'] !== UPLOAD_ERR_OK) {
                throw new Exception($this->getUploadError($file['error']), 400);
            }

            // 验证文件类型
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!in_array($file['type'], $allowedTypes)) {
                throw new Exception("只允许上传图片文件(jpg,png,gif,webp)", 400);
            }

            // 验证文件大小 (限制2MB)
            if ($file['size'] > 2 * 1024 * 1024) {
                throw new Exception("头像大小不能超过2MB", 400);
            }

            // 创建上传目录
            $uploadDir = 'uploads/avatars/' . date('Y/m/d');
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            // 生成唯一文件名
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $newFilename = 'avatar_' . $userId . '_' . time() . '.' . strtolower($ext);
            $relativePath = $uploadDir . '/' . $newFilename;
            $fullPath = $uploadDir . '/' . $newFilename;

            // 移动文件
            if (!move_uploaded_file($file['tmp_name'], $fullPath)) {
                throw new Exception("头像保存失败", 500);
            }

            // 返回完整URL路径
            $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
            $fileUrl = $baseUrl . '/api/' . $relativePath;
            // 更新用户头像字段
            $stmt = $this->conn->prepare("
                UPDATE users
                SET avatar = :avatar
                WHERE id = :id
            ");
            $stmt->execute([
                ':avatar' => $fileUrl,
                ':id' => $userId
            ]);


            echo json_encode([
                'code' => 200,
                'msg' => '头像上传成功',
                'data' => [
                    'avatar_url' => $fileUrl,
                    'avatar_path' => $relativePath
                ]
            ]);
        } catch (Exception $e) {
            // 保持 HTTP 状态码为 200，只在 JSON 响应中设置错误码
            echo json_encode([
                'code' => $e->getCode() ?: 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取上传错误信息
     */
    private function getUploadError(int $errorCode): string {
        switch ($errorCode) {
            case UPLOAD_ERR_INI_SIZE:
                return '上传的文件超过了php.ini中upload_max_filesize限制';
            case UPLOAD_ERR_FORM_SIZE:
                return '上传的文件超过了HTML表单中MAX_FILE_SIZE限制';
            case UPLOAD_ERR_PARTIAL:
                return '文件只有部分被上传';
            case UPLOAD_ERR_NO_FILE:
                return '没有文件被上传';
            case UPLOAD_ERR_NO_TMP_DIR:
                return '找不到临时文件夹';
            case UPLOAD_ERR_CANT_WRITE:
                return '文件写入失败';
            case UPLOAD_ERR_EXTENSION:
                return '上传被PHP扩展程序中断';
            default:
                return '未知上传错误';
        }
    }

    /**
     * 模拟获取微信用户信息 (实际项目中需要替换为真实的微信API调用)
     */
    private function getWechatUserInfo(string $code): array {
        // 这里应该调用微信API，以下是模拟返回
        return [
            'openid' => 'mock_openid_' . substr(md5($code), 0, 16),
            'unionid' => 'mock_unionid_' . substr(md5($code), 0, 16),
            'company' => '微信用户',
            'headimgurl' => ''
        ];
    }

    /**
     * 模拟验证短信验证码 (实际项目中需要替换为真实的短信验证码验证)
     */
    private function verifySmsCode(string $mobile, string $code): bool {
        // 这里应该调用短信验证服务，以下是模拟验证
        return $code === '123456'; // 测试时使用123456作为万能验证码
    }
}